//
//  MTRedpacketInfoDB.swift
//  MT
//
//  Created by ooops on 2020/5/20.
//  Copyright © 2020 张强. All rights reserved.
//

import Foundation
import FMDB
import JMessage
import MTCategory


/// 查看验证消息
enum MTRedpacketSourceType: Int {
    /// 所有类型请求消息
    case all
    /// 个人添加好友消息
    case single
    /// 申请加入群组验证消息
    case group
}

final class MTRedpacketInfoDB: NSObject {
    
    static let shareInstance = MTRedpacketInfoDB()
    
    var queue: FMDatabaseQueue?
    
    private override init() {
        super.init()
        _createDB()
    }
    
    private func _createDB() {
        let user = JMSGUser.myInfo()
        if user.username.isEmpty {
            return
        }
        let dir = user.username + user.appKey!
        
        var path = "\(NSHomeDirectory())/Documents/\(dir)"
        
        if createPath(path) {
            path = path + "/VerificationInfo.db"
            debugPrint(path)
            queue = FMDatabaseQueue(path: path)
            /// 创建好友列表 - 表结构
            /*
             * verType 1 - 好友申请, 2 - 俱乐部申请
             */
            let sql = "create table IF NOT EXISTS MTRedpacketInfo(msgId text, status integer, type integer)"
            
            queue?.inDatabase { (db) in
                db.executeUpdate(sql, withArgumentsIn: [])
            }
        }
    }
    
    func dropTable() {
        if queue == nil {
            _createDB()
            dropTable()
        }
        let sql = "drop table if exists MTRedpacketInfo"
        queue?.inDatabase { (db) in
            db.executeUpdate(sql, withArgumentsIn: [])
        }
    }
    
    func updateData(_ info: MTRedpacketInfo) {
        if queue == nil {
            _createDB()
            insertData(info)
        }
        let sql = "UPDATE MTRedpacketInfo SET status='\(info.status.rawValue)', type = \(info.type.rawValue)  WHERE type='\(info.type.rawValue)'"
        queue?.inDatabase { (db) in
            db.executeUpdate(sql, withArgumentsIn: [])
        }
    }
    
    func insertData(_ info: MTRedpacketInfo) {
        if queue == nil {
            _createDB()
            insertData(info)
        }
        let delSql = "delete from MTRedpacketInfo where msgId='\(info.msgId)'"
        queue?.inDatabase { (db) in
            db.executeUpdate(delSql, withArgumentsIn: [])
        }
        
        let sql = "insert into MTRedpacketInfo (msgId, status, type) values ('\(info.msgId)','\(info.status.rawValue)','\(info.type.rawValue)')"
        
        queue?.inDatabase { (db) in
            db.executeUpdate(sql, withArgumentsIn: [])
        }
    }
    
    func delete(_ info: MTRedpacketInfo) {
        if queue == nil {
            _createDB()
            insertData(info)
        }
        let delSql = "delete from MTRedpacketInfo where msgId = '\(info.msgId)')"
        queue?.inDatabase { (db) in
            db.executeUpdate(delSql, withArgumentsIn: [])
        }
    }
    
    /// 更新指定msgId的状态信息
    func updateRedpacketMessage(_ info: MTRedpacketInfo) {
        if queue == nil {
            _createDB()
        }
        
        let sql = "UPDATE MTRedpacketInfo SET status = '\(info.status.rawValue)' WHERE msgId = '\(info.msgId)'"
        queue?.inDatabase { (db) in
            _ = db.executeUpdate(sql, withArgumentsIn: [])
            //resultSet.close()
        }
    }
    
    /// 查询申请验证消息类型
    /// - Parameter verType: 筛选验证条件
    /// - 1 - 好友申请, 2 - 俱乐部申请, 0 - 所有消息
    func quaryData(msgId: String) -> [MTRedpacketInfo] {
        if queue == nil {
            _createDB()
            return []
        }
        var infos: [MTRedpacketInfo] = []
        let sql = "select * from MTRedpacketInfo  WHERE msgId='\(msgId)'"
        queue?.inDatabase { (db) in
            if let resultSet = db.executeQuery(sql, withArgumentsIn: []) {
                while (resultSet.next()) {
                    let info = MTRedpacketInfo()
                    info.msgId = (resultSet.string(forColumn: "msgId"))!
                    info.status = MTOpenRedpackStatus(rawValue: Int((resultSet.int(forColumn: "status"))))!
                    info.type = MTRedpacketType(rawValue: Int((resultSet.int(forColumn: "type"))))!
                    infos.append(info)
                }
                resultSet.close()
            }
        }
        return infos
    }
    
    // MARK: - private func
    private func createPath(_ path: String) -> Bool {
        var isDir: ObjCBool = ObjCBool(false)
        
        if FileManager.default.fileExists(atPath: path, isDirectory: &isDir) && isDir.boolValue {
            return true
        } else {
            try! FileManager.default.createDirectory(atPath: path, withIntermediateDirectories: true, attributes: nil)
            return true
        }
    }
}
